//引入vuex,因为我需要使用vuex存储得到的数据
import store from '@/store/index.js'

// 开启连接token = uni.getStorageSync('tokenWss') //token
export default {
	url: 'wss://imcnpe.knew-how.com/wss/default.io?token=', // WebSocket的url
	data: null,
	isCreate: false,
	isConnect: false, // 是否已经连接
	isInitiative: false, // 是否主动断开
	timeoutNumber: 20, // 心跳检测间隔(单位秒)
	heartbeatTimer: null, // 心跳检测定时器
	reconnectTimer: null, // 断线重连定时器
	socketExamples: null, // websocket实例
	againTime: 3, // 重连等待时间(单位秒)
	token: uni.getStorageSync('tokenWss'),

	// 初始化websocket连接
	createSocket(token) {

		const self = this
		try {
			self.socketExamples = uni.connectSocket({
				url: self.url + self.token,
				success: () => {
					self.isCreate = true
				},
				fail: () => {
					self.isCreate = false
				}
			})
		} catch (err) {
			console.log(err)
			console.log('websocket connection is abnormal, reconnecting...')
			self.reconnect(token)
		}
		self.initSocket()
		console.log(self.token)
	},

	// 创建websocket连接
	initSocket() {
		const self = this
		if (!self.isCreate) return
		self.socketExamples.onOpen(() => {
			console.log('WebSocket 连接成功')
			self.isConnect = true
			self.heartbeatTimer && clearInterval(self.heartbeatTimer)
			self.reconnectTimer && clearTimeout(self.reconnectTimer)
			// 打开心跳检测
			self.heartbeatCheck()
		})
		// 监听 WebSocket 接受到服务器的消息事件
		self.socketExamples.onMessage(({ data }) => {
			console.log('收到消息')
			console.log(JSON.parse(data))
			uni.$emit('message', JSON.parse(data))
		})
		// 监听 WebSocket 连接关闭事件
		self.socketExamples.onClose(() => {
			console.log('WebSocket 关闭了')
			self.isConnect = false
			self.reconnect()
		})
		// 监听 WebSocket 错误事件
		self.socketExamples.onError(res => {
			console.log('WebSocket 出错了')
			console.log(res)
			self.isInitiative = false
		})
	},

	// 发送消息
	sendMsg(value) {
		const param = JSON.stringify(value)
		return new Promise((resolve, reject) => {
			this.socketExamples.send({
				data: param,
				success(res) {
					console.log(res, '消息发送成功')
					// console.log('消息发送成功')
					resolve(true)
				},
				fail(error) {
					console.log('消息发送失败')
					reject(error)
				}
			})
		})
	},

	// 开启心跳检测
	heartbeatCheck() {
		let ping = { event: 'heartbeat' }
		// this.data = JSON.stringify(ping)
		// console.log(this.data)
		this.heartbeatTimer = setInterval(() => {
			this.sendMsg(ping)
			console.log('开启心跳检测')
		}, this.timeoutNumber * 1000)
	},

	// 重新连接
	reconnect() {
		// 停止发送心跳
		this.reconnectTimer && clearTimeout(this.reconnectTimer)
		this.heartbeatTimer && clearInterval(this.heartbeatTimer)
		// 如果不是人为关闭的话，进行重连
		if (!this.isInitiative) {
			this.reconnectTimer = setTimeout(() => {
				this.createSocket()
				console.log('重新连接')
			}, this.againTime * 1000)
		}
	},

	// 关闭 WebSocket 连接
	closeSocket(reason = '关闭') {
		const self = this
		this.socketExamples.close({
			reason,
			success() {
				self.data = null
				self.isCreate = false
				self.isConnect = false
				self.isInitiative = true
				self.socketExamples = null
				clearInterval(self.heartbeatTimer)
				clearTimeout(self.reconnectTimer)
				// console.log('关闭 WebSocket 成功')
			},
			fail() {
				console.log('关闭 WebSocket 失败')
			}
		})
	}
}